<template>
  <PageView
      ref="pageViewRef"
      :scrollable="false"
      :layout-vars="{showFooter:total>0}"
      v-loading="loading"
      :element-loading-text="loadingText"
  >
    <template #header>
      <div class="app-section-header">
        <el-form
            :model="queryParams"
            ref="queryForm"
            :inline="true"
            v-show="showSearch"
            label-width="68px"
        >
          <el-form-item
              label="运单号"
              prop="transportBillNumber"
          >
            <el-input
                v-model="queryParams.transportBillNumber"
                placeholder="请输入运单号"
                clearable
                @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item
              label="运单状态"
              prop="verifyStatus"
          >
            <el-select
                style="width: 130px"
                v-model="queryParams.transportBillStatus"
                placeholder="请选择"
                disabled
            >
              <el-option
                  v-for="item in queryParamsOptionsStates"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="">
            <el-select
                style="width: 130px"
                v-model="queryParams.timeType"
                placeholder="请选择"
                disabled
            >
              <el-option
                  v-for="item in queryTimeParamsOptions"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-date-picker
                v-model="dateRange"
                type="daterange"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
                unlink-panels
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                :shortcuts="shortcuts">
            </el-date-picker>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">查询</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
            <el-button type="danger" icon="Upload" @click="uploadQuery">推送当前页数据</el-button>
          </el-form-item>
        </el-form>
      </div>
    </template>

    <template v-slot:default="{contentHeight}">
      <el-table
          ref="table"
          :data="tableData"
          :height="contentHeight == 0 ? 200 : contentHeight"
          border
          scrollbar-always-on
          @selection-change="handleSelectionChange"
      >
        <el-table-column label="序号" type="index" width="55" align="center" />
        <el-table-column prop="transportBillNumber" label="运单号" width="180"  align="center"></el-table-column>
        <el-table-column prop="shipperTransportBillNumber" label="客户单号" width="180" align="center"></el-table-column>
        <el-table-column prop="transportBillStatusText" label="运单状态" width="180" align="center"></el-table-column>
        <el-table-column prop="riskStatusText" label="开票风险" width="180" align="center"></el-table-column>
        <el-table-column prop="shipperName" label="托运方名称" width="250" align="center">
          <template v-slot="scope">
            <div>{{scope.row.shipperInfoDTO.shipperName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="senderName" label="发货方名称" width="250" align="center">
          <template v-slot="scope">
            <div>{{scope.row.addressInfoDTO.senderName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="receiverLocation" label="收货方地址" width="250" align="center">
          <template v-slot="scope">
            <div>{{scope.row.addressInfoDTO.receiverLocation}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="carrierName" label="承运人名称" width="100" align="center">
          <template v-slot="scope">
            <div>{{scope.row.carrierInfoDTO.carrierName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="driverName" label="司机姓名" width="180" align="center">
          <template v-slot="scope">
            <div>{{scope.row.carrierInfoDTO.driverName}}</div>
          </template>
        </el-table-column>
        <el-table-column prop="goodsName" label="货物名称" width="180" align="center">
          <template v-slot="scope">
            <div>{{scope.row.goodsInfoDTO.goodsName}}</div>
          </template>
        </el-table-column>
      </el-table>
      <el-dialog
          :title="dialogTitle"
          v-model="dialogVisible"
          width='361px'
          append-to-body
      >
        <div v-for="(item, index) in urls">
          <ImagePreview
              class="info-image"
              :key="index"
              :width="321"
              :height="170"
              :src='item'
          />
        </div>
      </el-dialog>
    </template>

    <template #footer>
      <div class="app-section-footer">
        <Pagination
            v-show="total>0"
            :total="total"
            :pageSize="queryParams.pageSize"
            :currentPage="queryParams.pageNum"
            @pagination="getList"
        />
      </div>
    </template>

  </PageView>
</template>

<script lang="ts" setup>

</script>

<style>

</style>

<script>
/* eslint-disable */
import {getDriverInfo, getDriverImageInfo, getWaybillSearch} from "@/api/khy-operatingcenter";
import { uploadKhyWaybill } from '@/api/ky-api/ky-api'
import {getNowTimeStrWithFormatter, getTimestampByStr, getTimeWithFormatter} from '@/utils/util'

// 快货运 - 运单审核
export default {
  name: "WaybillSearch",
  components:{
  },
  props:{

  },
  data() {
    return {
      tableData:[],
      multipleSelection:[],

      // 加载状态
      loading:false,
      loadingText:null,

      // 分页相关参数
      total:0,

      // 是否显示搜索
      showSearch:true,

      // 查询参数相关
      queryParams:{
        pageNum:1,
        pageSize:100,
        transportBillNumber:null,
        // 只需要已签收的运单
        transportBillStatus:"60",
        businessScopeType: null,
        carLicensePlate: null,
        closeStatus: 0,
        companyId: null,
        creatorName:null,
        discardStatus:0,
        driverInvoiceStatus: null,
        driverName : null,
        driverPhone :null,
        informationPaymentBankAccountName:null,
        informationPaymentBankCardNumber:null,
        insuranceCompany:null,
        projectName: null,
        riskStatusList: [],
        routeName: null,
        shipperInvoiceStatus: null,
        shipperTransportBillNumber: null,
        taxSourceId: null,
        timeType: '5',

        // 开始时间 结束时间
        signStartTime: null,
        signEndTime :null,

        // 开始时间 结束时间
        startTime: null,
        endTime :null,
      },

      // 筛选时间
      queryTimeParamsOptions: [
        {
          value: '1',
          label: '开单时间',
        },
        {
          value: '2',
          label: '装货时间',
        },
        {
          value: '3',
          label: '卸货时间',
        },
        {
          value: '4',
          label: '创建时间',
        },
        {
          value: '5',
          label: '签收时间',
        },
      ],

      // 审核状态
      queryParamsOptionsStates: [
        {
          value: "",
          label: "全部",
        },
        {
          value: "20",
          label: "待指派",
        },
        {
          value: "30",
          label: "已指派",
        },
        {
          value: "40",
          label: "已装货",
        },
        {
          value: "50",
          label: "已卸货",
        },
        {
          value: "60",
          label: "已签收",
        },
        {
          value: "70",
          label: "已关闭",
        },
      ],

      // 日期范围
      dateRange: [],
      // 开始结束时间级联事件选择配置数据 - 最近时间
      shortcuts:[
        {
          text: '最近一周',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
            return [start, end]
          },
        },
        {
          text: '最近一个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
            return [start, end]
          },
        },
        {
          text: '最近三个月',
          value: () => {
            const end = new Date()
            const start = new Date()
            start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
            return [start, end]
          },
        },
      ],

      // 控制弹窗显示
      dialogVisible:false,
      dialogTitle:"查看",
      urls:[],
    }
  },
  beforeCreate() {

  },
  setup() {

  },
  created() {
    // 默认查询2020年至上上天23:59:59
    // 两个月内的 截止时间为上上一天零点
    let nowTime = new Date() - 2 * 24 * 3600 * 1000;
    let endTime = getTimeWithFormatter(nowTime, 'yyyy-MM-dd');
    this.dateRange = ['2018-01-01', endTime];

    this.getList()
  },
  mounted() {
    console.log('路由传入的参数信息', this.$route.query)
    console.log('获取分页数据')
  },
  activated() {
    console.log('keep-alive被激活时调用')
  },
  methods:{
    getList(pageInfo) {
      this.loading = true
      this.updatePageInfo(pageInfo)

      let param = this.getParams()
      getWaybillSearch(param).then(res => {
        const result = res.data ? res.data : {}
        this.loading = false
        this.total = result.total
        this.tableData = result.records
      }).catch(err => {
        console.log('获取运单查询数据失败：', err)
      })
    },

    /**
     * 获取请求参数
     * @returns {{transportBillNumber: null, closeStatus: number, informationPaymentBankCardNumber: null, shipperInvoiceStatus: null, carLicensePlate: null, creatorName: null, pageSize: number, timeType: string, businessScopeType: null, transportBillStatus: null, routeName: null, driverInvoiceStatus: null, startTime: number, taxSourceId: null, insuranceCompany: null, informationPaymentBankAccountName: null, riskStatusList: [], pageNum: number, companyId: null, discardStatus: number, shipperTransportBillNumber: null, driverName: null, driverPhone: null, endTime: number, projectName: null}}
     */
    getParams() {
      let startTime = null;
      let endTime = null;
      if (this.dateRange && this.dateRange.length > 0) {
        let str = this.dateRange[0] + ' 00:00:00'
        startTime = getTimestampByStr(str);
        console.log('startTime:', startTime)
      }
      if (this.dateRange && this.dateRange.length > 1) {
        let str = this.dateRange[1] + ' 23:59:59:999'
        endTime = getTimestampByStr(str);
        console.log('endTime:', endTime);
      }
      this.queryParams.signStartTime = startTime;
      this.queryParams.signEndTime = endTime;
      return this.queryParams
    },

    /**
     * 获取展示的时间
     * @param time
     * @returns {string}
     */
    getShowTime(time, formatter) {
      return getTimeWithFormatter(time, formatter)
    },

    /**
     * 分页组件变动 更新分页标记数据
     * @param val
     */
    updatePageInfo(val) {
      if (val) {
        this.queryParams.pageSize = val.pageSize
        this.queryParams.pageNum = val.pageNum
      }
    },

    /**
     * 单元格多选方法
     * @param val
     */
    handleSelectionChange(selection) {
      this.multipleSelection = selection;
      console.log('当前选择的单元格数据', this.multipleSelection)
    },

    /**
     * 搜索按钮点击事件
     */
    handleQuery() {
      console.log('handleQuery:', this.queryParams)
      console.log('dateRange:', this.dateRange)
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /**
     * 查询表单重置
     */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm")
      this.handleQuery()
    },

    /**
     * 将查询到的数据同步保存至开运系统
     */
    uploadQuery() {
      if (this.tableData.length == 0) {
        return
      }
      let platform = this.$store.state.customerName;;
      let custom = this.$store.state.user.name;
      let queryParam = this.getParams();
      let data = this.tableData;
      let info = {}
      info.platform = platform
      info.custom = custom
      info.queryParam = queryParam
      info.data = data
      info.dataType = 1;
      this.loading = true;
      this.loadingText = "导入中..."
      uploadKhyWaybill(info).then(res => {
        console.log('导入运单数据到开运成功')
        this.loading = false
        this.$message.success('本页数据导入成功')
      }).catch(err => {
        console.log('导入运单数据到开运失败')
        this.loading = false
      })
    },

    /**
     * 姓名点击事件
     */
    nameClicked() {
      // 开一个新的二级页面
      this.$router.push('/main/userInfo')
    },

    /**
     * 弹窗关闭
     */
    handleClose() {
      this.dialogVisible = false
    },

    editBtnClicked() {
      console.log('编辑')
    },

    deleteBtnClicked() {
      console.log('删除')
      this.$modal.showConfirmAlert('提示', '确认删除吗?')
          .then(() => {

            this.$message.success('删除成功')
          })
          .catch(() => {
            this.$message.info('取消')
          })
    },


    /**
     * 查看司机详情信息图片
     * @param scope 查看行
     * @param type 查看类型 0身份证图片
     */
    scanDriverInfo(scope, type) {
      if (scope) {
        let row = scope.row
        let title = scope.column.label
        let str = ''
        let arr = []
        if (type == 0) {
          // 身份证
          arr.push(row.idCardFrontFilename);
          arr.push(row.idCardBackFilename);
        }
        const param = {
          filenames:arr
        }

        let imageUrls = []
        getDriverImageInfo(param).then(res => {
          console.log('获取图片信息：', res)
          let data = res.data ? res.data : {}
          for (const imageKey of arr) {
            const imageInfo = data[imageKey]
            const imageUrl = imageInfo.url
            imageUrls.push(imageUrl)
          }
          console.log('imageUrls:', imageUrls)
          this.urls = imageUrls
          this.dialogTitle = title
          this.dialogVisible = true
        }).catch(err => {
          console.log('获取图片信息失败：', err)
        })
      }
    },
  }
}
</script>

<style lang="scss" scoped>
// 引入公共样式文件 scss
@import '../../assets/styles/public.scss';

/*在elementUI中，row-class-name、row-style、cell-class-name等属性要想生效必须使用全局class才能生效。可以写到一个样式文件中 引入即可*/
.el-table .warning-row {
  background-color: $warning-color;
}

.el-table .success-row {
  background-color: $success-color;
}

.el-table .danger-row {
  background-color: $danger-color;
}

// 查看docx文档时 生成的盒子
:deep(.docx-wrapper) {
  background-color: #fff;
  padding: 0;
}

:deep(.docx-wrapper > section.docx) {
  width: 100% !important;
  padding: 0rem !important;
  min-height: auto !important;
  box-shadow: none;
  margin-bottom: 0;
}

</style>
